<?php
namespace App\Services;

use App\Models\TourStatistics;
use App\Models\TourTuan;
use App\Models\TourTuanData;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 *
 * 路线拼团信息服务层
 *
 * @author shengl
 *
 */
class TourTuanService extends BaseService {

    /**
     * 指定线路Id获取团列表
     * @param int $user_id 用户id
     * @param int $tour_id 线路id
     * @param int $tuan_type 团类型 公开或者私有
     * @param $firstrow
     * @param $pagesize
     * @return array
     */
    public function getTuanList($user_id=0,$tour_id=0,$tuan_type=TOUR_TUAN_TYPE_PUBLIC,$firstrow=0,$pagesize=10){

        $query = TourTuan::with(['tour'=>function($query){
            $query->select('tour_id','tour_name','short_name','default_image','to_region_name');
        },'tour.tourExtra'=>function($query){
            $query->select('tour_id','travel_days');
        },'tourTuanData'=>function($query){
            $query->where('state',TUAN_DATA_STATE_SUCCESS)->select('tuan_id','user_id','nickname','copies','portrait');
        }])->where('state',TUAN_STATE_WAITE)->where('tuan_type',$tuan_type);

        if($tour_id){
            $query->where('tour_id',$tour_id);
        }

        $tourTuanList = $query->select('tuan_id','tour_id','state','slogan','start_time','end_time','copy_tour_date','copy_peoples','rest_copies','copy_price','tuan_type','copy_config')->orderBy('start_time','desc')->skip($firstrow)->take($pagesize)->get();

        if(!$tourTuanList){
            return $this->failure('该路线占无人员开启团购');
        }

        foreach($tourTuanList as $item){
            $item->start_time_fmt= local_date('Y-m-d H:i',$item->start_time);
            $item->end_time_fmt= local_date('Y-m-d H:i',$item->end_time);
            $item->copy_tour_date_fmt= local_date_ymd($item->copy_tour_date);
            $peoples = json_decode($item->copy_config,true);
            $item->copy_peoples = $item->copy_peoples /($peoples['limit_a'] + $peoples['limit_c']);
            $item->rest_copies = $item->rest_copies /($peoples['limit_a'] + $peoples['limit_c']);
            if($peoples['limit_c']>0){
                $item->peoplesfen = '包含'.$peoples['limit_a'].'个成人'.$peoples['limit_c'].'个儿童';
            }else{
                $item->peoplesfen = '包含'.$peoples['limit_a'].'个成人';
            }

            $item->tour->default_image = complete_url($item->tour->default_image);
            $item->state_text = self::getTuanStateText($item->state);
            $item->tuan_type_text = self::getTuanTypeText($item->tuan_type);
            $item->is_joined = NO;
            $item->joined_copies = 0;
            foreach($item->tourTuanData as $tuanData){
                if($user_id == $tuanData->user_id){
                    $item->is_joined = YES;
                }
                $item->joined_copies += $tuanData->copies;
                unset($tuanData->tuan_id,$tuanData->user_id);
                $tuanData->portrait = complete_url($tuanData->portrait);
            }
        }

        return $this->success($tourTuanList);

    }

    /**
     * 获取用户所参与的旅游的团列表
     * @param int $user_id 用户id
     * @param string $tuan_state 团状态 全部 all/组团中 waiting/已成团 succeed/组团失败 failed
     * @param $firstrow
     * @param $pagesize
     * @return array
     */
    public function getMyTuanList($user_id=0,$tuan_state='all',$firstrow=0,$pagesize=10){

        $tuanids = TourTuanData::where('user_id',$user_id)
            ->where('state',TUAN_STATE_SUCCESS)
            ->pluck('tuan_id');

        //dd($tuanids);
        if(count($tuanids) == 0){
            return $this->success();
        }

        $query = TourTuan::with(['tour'=>function($query){
            $query->select('tour_id','tour_name','short_name','default_image','to_region_name');
        },'tour.tourExtra'=>function($query){
            $query->select('tour_id','travel_days');
        },'tourTuanData'=>function($query){
            $query->select('tuan_id','user_id','nickname','copies','portrait','state as tuan_data_state')
                    ->where('state',TUAN_DATA_STATE_SUCCESS);
        }])->whereIn('tuan_id',$tuanids);

        switch($tuan_state){
            case 'waiting':
                $query->where('state',TUAN_STATE_WAITE);
                break;
            case 'succeed':
                $query->where('state',TUAN_STATE_SUCCESS);
                break;
            case 'failed':
                $query->where('state',TUAN_STATE_FAILURE);
                break;
            default:
                $query->where('state','<>',TUAN_STATE_DEFAULT);
        }

        $query->select('tuan_id','tour_id','state as tuan_state','slogan','start_time','end_time','copy_tour_date','copy_peoples','rest_copies','copy_price','tuan_type','copy_config');
        $query->skip($firstrow)->take($pagesize)
            ->orderBy('start_time','desc');

        $tourtuans = $query->get();

        $myTuanList = [];
        foreach($tourtuans as $item){
            $item->start_time_fmt= local_date('Y-m-d H:i',$item->start_time);
            $item->end_time_fmt= local_date('Y-m-d H:i',$item->end_time);
            $item->copy_tour_date_fmt= local_date_ymd($item->copy_tour_date);
            $peoples = json_decode($item->copy_config,true);
            $item->copy_peoples = $item->copy_peoples /($peoples['limit_a'] + $peoples['limit_c']);
            $item->rest_copies = $item->rest_copies /($peoples['limit_a'] + $peoples['limit_c']);
            if($peoples['limit_c']>0){
                $item->peoplesfen = '包含'.$peoples['limit_a'].'个成人'.$peoples['limit_c'].'个儿童';
            }else{
                $item->peoplesfen = '包含'.$peoples['limit_a'].'个成人';
            }
            $item->tour->default_image = complete_url($item->tour->default_image);
            $item->state_text = self::getTuanStateText($item->state);
            $item->tuan_type_text = self::getTuanTypeText($item->tuan_type);
            $item->joined_copies = 0;

            foreach($item->tourTuanData as $tuanData){
                $item->joined_copies += $tuanData->copies;
                unset($tuanData->tuan_id,$tuanData->user_id);
                $tuanData->portrait = complete_url($tuanData->portrait);

            }
            $myTuanList[] = $item;
            unset($item);
        }
        return $this->success($myTuanList);

    }

    /**
     * 获取用户所参与的旅游的团列表
     * @param int $user_id 用户id
     * @param $tuan_id 团id
     * @return array
     */
    public function getTuanDetail($user_id=0,$tuan_id){

        $query = TourTuan::with(['tour'=>function($query){
            $query->select('tour_id','store_id','tour_name','short_name','default_image','to_region_name','tags','price_a','adult_child_joinflg');
        },'tour.tourExtra'=>function($query){
            $query->select('tour_id','travel_days');
        },'tour.store'=>function($query){
            $query->select('store_id','owner_name','tel');
        },'tourTuanData'=>function($query){
            $query->where('state',TUAN_DATA_STATE_SUCCESS)->select('tuan_id','user_id','order_id','nickname','copies','portrait');
        }])->where('state','<>',TUAN_STATE_DEFAULT);


        $tourTuan = $query->select('tuan_id','tour_id','state','slogan','start_time','end_time','copy_tour_date','copy_peoples','rest_copies','copy_price','tuan_type','copy_config')->find($tuan_id);

        if(!$tourTuan){
            return $this->failure('未找到该团购信息');
        }
        $peoples = json_decode($tourTuan->copy_config,true);
        $tourTuan->copy_peoples =$tourTuan->copy_peoples /($peoples['limit_a'] + $peoples['limit_c']);
        $tourTuan->rest_copies = $tourTuan->rest_copies /($peoples['limit_a'] + $peoples['limit_c']);
        if($peoples['limit_c']>0){
            $tourTuan->peoplesfen = '包含'.$peoples['limit_a'].'个成人'.$peoples['limit_c'].'个儿童';
        }else{
            $tourTuan->peoplesfen = '包含'.$peoples['limit_a'].'个成人';
        }
        $time = DB::table('config')->where('code','tuan_info_endtime')->value('value');//未支付订单存活时间商品 配置
        $tourTuan->start_time_fmt= local_date('Y-m-d H:i',$tourTuan->start_time);
        $tourTuan->end_time_fmt= local_date('Y-m-d H:i',$tourTuan->end_time);
        if($tourTuan->state ==1){
            $tourTuan->rest_time = 0;
        }elseif($tourTuan->state == 2){
            $tourTuan->rest_time = 0;
        }else{
            $tourTuan->rest_time = $tourTuan->end_time - gmtime();
        }
        if($tourTuan->end_time <= gmtime()){
            $tourTuan->can_joingroup = 0;
        }else{
            $tourTuan->can_joingroup = 1;
        }
        $tourTuan->copy_tour_date_fmt= local_date_ymd($tourTuan->copy_tour_date);

        $tourTuan->tour->default_image = complete_url($tourTuan->tour->default_image);
        $tourTuan->state_text = self::getTuanStateText($tourTuan->state);
        $tourTuan->tuan_type_text = self::getTuanTypeText($tourTuan->tuan_type);
        $tourTuan->is_joined = NO;
        $tourTuan->joined_copies = 0;
        foreach($tourTuan->tourTuanData as $tuanData){
            if($user_id == $tuanData->user_id){
                $tourTuan->is_joined = YES;
                $tourTuan->order_id = $tuanData->order_id;
            }
            $tourTuan->joined_copies += $tuanData->copies;
            unset($tuanData->tuan_id,$tuanData->user_id,$tuanData->order_id);
            $tuanData->portrait = complete_url($tuanData->portrait);
        }
        $user_info=DB::table('member')->where('user_id',$tourTuan->tour->store->store_id)->first();
        $tourTuan->tour->store->owner_name =  $user_info->real_name;
        $tourTuan->tour->store->tel =  $user_info->phone_mob;
        $tourTuan->tour->min_price = $tourTuan->tour->price_a;

        return $this->success($tourTuan);

    }

    public static function getTuanStateText($state){
        switch($state){
            case TUAN_STATE_WAITE:
                $state_text = '团购中';
                break;
            case TUAN_STATE_SUCCESS:
                $state_text = '团购完成';
                break;
            case TUAN_STATE_FAILURE;
                $state_text = '团购失败';
                break;
            default:
                $state_text = '无效团';
        }

        return $state_text;
    }

    public function changeTuanStock($type='-',$tuan_id,$quantity,$withTrans = true)
    {
        if($quantity == 0){
            return;
        }

        /* 获取订单商品列表 */
        $tourtuan = TourTuan::find($tuan_id);

        if($withTrans){
            DB::beginTransaction();
        }
        try {
            /* 依次改变库存 */
            if ($type == '-') {
                if($quantity > $tourtuan->stock_defined - $tourtuan->saled_cnt){
                    $tourtuan->stock = 0;
                }else{
                    $tourtuan->stock-= $quantity;
                }
                $tourtuan->saled_cnt += $quantity;
                TourStatistics::where('tour_id', $tourtuan->tour_id)->increment('sales', $quantity);
            } else {
                if($tourtuan->stock_defined > $tourtuan->saled_cnt){
                    $tourtuan->stock+=$quantity;
                }
                $tourtuan->saled_cnt -= $quantity;
                TourStatistics::where('tour_id', $tourtuan->tour_id)->decrement('sales', $quantity);
            }
            $tourtuan->save();

            if($withTrans){
                DB::commit();
            }

        }catch (\Exception $e){
            Log::ERROR($e->getMessage());
            if($withTrans){
                DB::rollback();
            }
        }
    }

    public static function getTuanTypeText($tuan_type){
        switch($tuan_type){
            case TOUR_TUAN_TYPE_PUBLIC:
                $tuan_type_text = '所有人';
                break;
            case TOUR_TUAN_TYPE_PRIVATE:
                $tuan_type_text = '需要密码';
                break;
            default:
                $tuan_type_text = '所有人';
        }

        return $tuan_type_text;
    }

}